import datetime
from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class goods:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'goods')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 获取商品列表
    def get_goods_list(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = "where 1=1 "
        sql = ""
        if data != {}:
            if data.get('goodsName') is not None:
                if data['goodsName'] != '':
                    sql = sql + " and `goods_name` like '%{}%'".format(data['goodsName'])
 
            if data.get('status') is not None:
                if data['status'] != '':
                    sql = sql + " and `status`='{}'".format(data['status'])
          
        total = self.db.get(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY `order_num` ASC '
        else:
            sql = sqls + ' ORDER BY `order_num` ASC '
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                
                # 循环处理获得category_name
                category_ids = r.get('category_id').split(',')
                category_name = []
                for c in category_ids:
                     res = self.db.gets(f"SELECT `category_name` FROM category WHERE `category_id`='{c}'")
                     category_name.append( res[0].get('category_name'))
                r['category_name'] =  category_name
                
                #循环处理goods_tags
                if r.get('goods_tags') is not None and r.get('goods_tags') != '':
                    r['goods_tags'] =  r.get('goods_tags').split(',')
                else:
                    r['goods_tags'] =  None
                    
                result['data'].append(r)
        result = self.cf.changes_format(result)
        
        return result


    # 新增
    def add_goods(self, data,userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `goods_name`='{data['goodsName']}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 500
            result['msg']= '商品名称重复'
        else:
            data['create_by'] = userInfo['userName']
            data['create_time'] = times 
            add_sql = self.sm.add_sql_data(data, 'goods')
            goods_id = self.db.adds(add_sql, 'goods')
            
            if data['attributeList'] is not None:
                for a in data['attributeList']:
                    a['goodsId'] = goods_id
                    
                    if 'id' in a and a['id'] is not None and a['id'] != '':
                        edit_sql = self.sm.edit_sql_data(a, 'goods_attributes', 'id', a['id'])
                        self.db.edits(edit_sql, 'goods_attributes')
                    else:
                        add_sql_o = self.sm.add_sql_data(a, 'goods_attributes')
                        self.db.adds(add_sql_o, 'goods_attributes')
        return result
    

    # 修改
    def edit_goods(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `goods_name`='{data['goodsName']}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['goods_id'] == data['goodsId']:
                    ff = True
                else:
                    if g['goods_name'] == data['goodsName']:
                        result['msg'] = '商品名称重复'
                    ff = False
                    result['code'] = 500
                    break
        else:
            ff = True
        if ff:
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'goods', 'goods_id', data['goodsId'])
            self.db.edits(edit_sql, 'goods')
         
        # 获取属性表里所有的选项
        s_sql = f"select `id` from `goods_attributes` where `goods_id`='{data['goodsId']}'"
        s_res = self.db.gets(s_sql) 
        # 传入的产品属性
        params_options = []    
        if data['attributeList'] is not None:
            for a in data['attributeList']:
                a['goodsId'] = data['goodsId']
                if 'id' in a and a['id'] is not None and a['id'] != '':
                    edit_sql = self.sm.edit_sql_data(a, 'goods_attributes', 'id', a['id'])
                    self.db.edits(edit_sql, 'goods_attributes')
                    params_options.append(a['id'])
                else:
                    add_sql_o = self.sm.add_sql_data(a, 'goods_attributes')
                    self.db.adds(add_sql_o, 'goods_attributes')
                    
         #没有传入的选项，走删除操作
        for s in s_res:
            try:
                index = params_options.index(s['id'])
            except ValueError:
                dtd_sql = f"delete from `goods_attributes` where `id`='{s['id']}'"
                self.db.edits(dtd_sql, 'goods_attributes')             
        return result

    
    # 查看
    def get_goods(self, goodsId):
        result = {'msg': '成功', 'code': 200, 'data': {}}
        sql = f"where `goods_id`='{goodsId}'"
        res = self.db.get(sql)
        if res[0].get('goods_tags') is not None and res[0].get('goods_tags') != '':
            res[0]['goods_tags'] =  res[0].get('goods_tags').split(',')
        else:
            res[0]['goods_tags'] =  None
            
        # 查询关联标签
        gId_sql = f"select * from `goods_attributes` where `goods_id`='{goodsId}'"
        gId_res = self.db.gets(gId_sql)
        res[0]['attribute_list'] = []
        
        if gId_res != ():
            for g in gId_res:
                g['option_ids'] =  [int(i) for i in g['option_ids'].split(',')]
            res[0]['attribute_list'] = gId_res
            
        result['data'] = res[0]
        result = self.cf.changes_format(result)
        return result

    # 删除
    def del_goods(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            # 删除
            dr_sql = f"where `goods_id`={i}"
            self.db.delete(dr_sql)
        return result
